<template>
	<div>
		<el-tree :data="menuList" :props="defaultProps" :default-expand-all="true" node-key="id" @check-change="handleCheckChange">
			<template #defult="{ node, meta }">
				<span class="custom-tree-node">
					<el-checkbox v-model="node.checked" :disabled="node.disabled"></el-checkbox>
					<span>{{ meta.title }}</span>
				</span>
			</template>
		</el-tree>
	</div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { ElTree } from "element-plus";
interface MenuNode extends Menu.MenuOptions {
	checked: boolean;
	children: MenuNode[];
}
export default defineComponent({
	name: "PermissionMenu",
	components: {
		ElTree
	},
	props: {
		menuList: {
			type: Array as () => MenuNode[],
			required: true
		}
	},
	data() {
		return {
			defaultProps: {
				children: "children",
				label: "name"
			}
		};
	},
	methods: {
		handleCheckChange(data: MenuNode, checked: boolean, node: any) {
			data.checked = checked;

			if (data.children) {
				this.checkChildren(data.children, checked);
			}

			if (node.parent && !checked) {
				this.handleParentCheckChange(node.parent);
			}
		},
		checkChildren(children: MenuNode[], checked: boolean) {
			children.forEach(child => {
				child.checked = checked;

				if (child.children) {
					this.checkChildren(child.children, checked);
				}
			});
		},
		handleParentCheckChange(parentNode: any) {
			if (parentNode) {
				const siblings = parentNode.childNodes;

				if (siblings.every((sibling: any) => !sibling.checked)) {
					parentNode.checked = false;
					this.handleParentCheckChange(parentNode.parent);
				} else if (siblings.every((sibling: any) => sibling.checked)) {
					parentNode.checked = true;
					this.handleParentCheckChange(parentNode.parent);
				} else {
					parentNode.checked = false;
				}
			}
		}
	}
});
</script>
